﻿namespace 事件驱动;

using ArgsCallback = Action<object[]>;
using NoArgsCallback = Action;

/// <summary>
/// 事件发射器
/// </summary>
public class EventEmitter
{
    /// <summary>
    /// 事件总线
    /// </summary>
    private readonly Dictionary<string, ICollection<NoArgsCallback>> _eventBus = new();
    
    public EventEmitter Emit(string eventName, params object[] args)
    {
        if (!CheckEvent(eventName))
        {
            return this;
        }
       

        var actionList = _eventBus[eventName];
        if (actionList.Count == 0)
        {
            return this;
        }
        
        actionList.ToList().ForEach(action =>
        {
            action();
        });

        return this;
    }

    public EventEmitter On(string eventName, NoArgsCallback callback)
    {
        if (!CheckEvent(eventName))
        {
            return this;
        }

        var callbackList = _eventBus[eventName];
        callbackList.Add(callback);
        return this;
    }
    
    
    private bool CheckEvent(string eventName)
    {
        if (_eventBus.ContainsKey(eventName))
        {
            _eventBus.Add(eventName, new LinkedList<NoArgsCallback>());
            return false;
        }
        return true;
    }
}